package com.math.aistudykbr.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.math.aistudykbr.config.SSEConnectManager;
import com.math.aistudykbr.constant.MessageConstants;
import com.math.aistudykbr.pojo.entity.MyMessage;
import com.math.aistudykbr.service.AIService;
import com.math.aistudykbr.utils.Result;
import com.math.aistudykbr.utils.UserContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.List;

@RestController
@RequestMapping("/api/ai")
@Slf4j
@RequiredArgsConstructor
public class AIController {

    private final AIService aiService;

    private final SSEConnectManager sseConnectManager;

    /**
     * 聊天接口
     * @param msg
     * @return
     */
    @GetMapping("/chat")
    public Result<String> aiChat(@RequestParam String msg) throws JsonProcessingException {
        log.info("用户userId={}发送消息：{}", UserContext.getUser(), msg);
        return Result.success(200, "聊天成功", aiService.chatWithAI(UserContext.getUser(), msg));
    }

    @GetMapping(value = "/fluxChat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public void fluxChat(@RequestParam String msg) throws JsonProcessingException {
        log.info("用户 userId={} 开始流式聊天", UserContext.getUser());
        // 1. 从全局存储中获取emitter
        SseEmitter emitter = sseConnectManager.getConnection(UserContext.getUser().toString());

        if (emitter == null) throw new RuntimeException(MessageConstants.SSENotFound);

        // 2. 发送消息
        aiService.chatWithAIFlux(emitter, msg);
    }

    /**
     * 获取历史消息
     * @return
     */
    @GetMapping("/getMsg")
    public Result<List<MyMessage>> getHistoryMsg() {
        log.info("用户userId={}获取历史消息", UserContext.getUser());
        return Result.success(200, "获取历史消息成功", aiService.getHistoryMsg(UserContext.getUser()));
    }

    /**
     * 删除上下文
     * @return
     */
    @DeleteMapping("/deleteContext")
    public Result<String> deleteContext() {
        aiService.deleteContext(UserContext.getUser());
        return Result.success(200, "删除用户上下文成功", null);
    }

    /**
     * 删除历史消息
     * @return
     */
    @DeleteMapping("/deleteHistoryMsg")
    public Result<String> deleteHistoryMsg() {
        aiService.deleteHistoryMsg(UserContext.getUser());
        return Result.success(200, "删除历史消息成功", null);
    }
}
